"use strict";
const ACTION_SET = {
	GET_MOCKTEST_DATA: "getMockData",
	OPEN_ALL_JIGOU_QUESLIST: 'openAllQuesctionList',
	CHECK_USER_ACTIVITY: 'checkUserActivity',
	GET_BANNER:'getBanner',
	GET_VIDEO:'getVideo',
	GET_HOME:'getHome',
	GET_ERROR_COUNT:'getErrorCount'
	
};
const db = uniCloud.database();
const cmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log("event : ", event);



	let {
		ACTION,
		drive,
		subject
	} = event;
	let result = {};
	
	if (event.timingTriggerConfig) {
		ACTION = 'checkUserActivity'
	}
	
	console.log('run action', ACTION)
	const AnsOfLable = {
		'A': '0',
		'B': '1',
		'C': '2',
		'D': '3',
		'E': '4',
		'F': '5',
	}

	const labelAns = {
		'0': 'A',
		'1': 'B',
		'2': 'C',
		'3': 'D',
		'4': 'E',
		'5': 'F'
	}
	const shuffle = (arr) => {
		var l = arr.length
		var index, temp
		while (l > 0) {
			index = Math.floor(Math.random() * l)
			temp = arr[l - 1]
			arr[l - 1] = arr[index]
			arr[index] = temp
			l--
		}
		return arr
	}
	const resort = (struct, s_ans) => {

		let arr = []
		let n_ans = [] //重置后的答案
		let s_ans_arr = s_ans.split('|') //重置前答案
		let s_ans_index = []
		for (let s of s_ans_arr) {
			s_ans_index.push(parseInt(AnsOfLable[s]))
		}

		struct.forEach((e, i) => {
			if (s_ans_index.includes(e.index)) {
				arr.push(i)
				n_ans.push(labelAns[`${i}`])
			}
		})
		return {
			realAns: n_ans.join('|'),
			realIndex: arr.join(',')
		}
	}
	
	const getHome = async () =>{
		const mechinsList = await db.collection('news-articles')
			.where({
				category_id: '631f82da7d77c300015e1a94'
			})
			.field({_id:true,title:true,image:true})
			.get()
			
		const activeUserCount = await db.collection('action-user').count()	
		
		const resultList = await db.collection('adv-meclist').orderBy('sort', 'asc').get()
		
		const type = '6d85a2b962aaf2f30aee304238614502'
		const article = await db.collection('news-articles').where({
				category_id: '6d85a2b962aaf2f30aee304238614502',
				article_status: 1
			})
			.orderBy('publish_date', 'desc').limit(3).get()
			
		return {
			mechinsList:mechinsList.data,
			activeUserCount:activeUserCount,
			adv_resultList:resultList.data,
			article_list:article.data
		}
	}
	
	const getVideo = async()=>{
		let videoResult = await db.collection('adv-video').limit(1).get()
		if (videoResult.data.length > 0) {
			return videoResult.data[0].video_src
		}else{
			return ''
		}
	}
	
	const checkUserActivity = async () => {
		let now = (new Date).getTime()
		console.log(now)
		const exporise = await db.collection('action-user').where({
			token_expired: cmd.lte(now)
		}).remove()
		return exporise.data
	}
	
	const getBanner = async () =>{
		const bannerList = await db.collection('banner').orderBy('sort','asc').get()
		if (bannerList.data.length > 0) {
			return bannerList.data
		}else{
			return [] 
		}
	}
	
	const getMockData = async () => {
		let qlstore = null;
		let qsAns = []
		let ql = []
		let qlClone = []
		let subjectName = '仿真考试'
		let paper = null
		let test = null
		let paperlist = null
		let sortMap = {
			2: [],
			0: [],
			1: []
		}
		let index = 0
		let merId = event.mer_id ? event.mer_id : ''
		let testRoleInfo = await db
			.collection("test-role")
			.where({
				type_drive_id: drive,
				type_subject_id: subject,
				mer_id:db.command.eq(merId)
			})
			.limit(1)
			.get();
			
			if(testRoleInfo.data.length === 0){
				 testRoleInfo = await db.collection('test-role').where({
						type_drive_id: db.command.eq(drive),
						type_subject_id: db.command.eq(subject),
						mer_id:db.command.eq('')
						}).limit(1).get()
						
			}
			
			
		if (testRoleInfo.data.length > 0) {
			const _role = testRoleInfo.data[0];
			const roleItem = await db
				.collection("role-item")
				.where({
					_id: db.command.in(_role.role_item_ids),
				})
				.get();
			let q_type = {
				radio: 0,
				multiple: 1,
				judge: 2,
			};

			for (let s of roleItem.data) {
				let tempdata = await db
					.collection("test-paper")
					.where({
						s_id: cmd.eq(s.test_paper_id),
					})
					.field({
						_id: true,
						name: true,
						quesction_list: true,
						s_id: true,
					})
					.limit(1)
					.get();

				for (let r of ["radio", "multiple", "judge"]) {
					if (s[r] > 0) {
						const dt = await db
							.collection("quesction")
							.aggregate()
							.match({
								s_id: cmd.in(tempdata.data[0].quesction_list),
								q_type: cmd.eq(q_type[r]),
							})
							.sample({
								size: s[r],
							})
							.limit(s[r])
							.end();

						for (let sq of dt.data) {
							sq.infoname = subjectName;
							if (sq.q_type != 2) {
								sq.q_struct = shuffle(sq.q_struct);
								sq.realProps = resort(sq.q_struct, sq.q_ans);
							}
							sq.check = [false, false, false, false, false, false];
							ql.push(sq);
							sortMap[sq.q_type].push(index);
							index++;
						}
					}
				}
			}

			for (let j of sortMap[2]) {
				qlClone.push(ql[j]);
			}
			for (let j of sortMap[0]) {
				qlClone.push(ql[j]);
			}
			for (let j of sortMap[1]) {
				qlClone.push(ql[j]);
			}
		}
		return qlClone
	};

	const openAllQlist = async () => {

		const subjectPageList = await db.collection('subject-page').field({
			_id: true,
			s_id: true
		}).limit(500).get()
		const mechinsmList = await db.collection('mechanism').field({
			_id: true,
			s_id: true
		}).limit(500).get()
		const curHasMec = await db.collection('mechanism-subject-list').field({
			_id: true,
			mechanism_id: true
		}).limit(500).get()

		let subjectList = []
		let hasMecList = new Map()


		for (let s of subjectPageList.data) {
			subjectList.push(s.s_id)
		}

		for (let s of curHasMec.data) {
			hasMecList.set(s.mechanism_id, true)
		}
		let successNum = 0
		for (let s of mechinsmList.data) {
			if (hasMecList.get(s._id)) {
				const updateRes = await db.collection('mechanism-subject-list').where({
					mechanism_id: s._id
				}).update({
					subject_id: subjectList
				})
				console.log('更新成功!', updateRes)
			} else {
				const addRes = await db.collection('mechanism-subject-list').add({
					mechanism_id: s._id,
					subject_id: subjectList
				})
				console.log('新增成功!', addRes)
			}
			successNum++
		}
		return successNum
	}
	
	const getErrorCount = async ()=>{
		const response = await db.collection('error-qlist').where({
			user_id: event.uid
		}).count()
		return response.total
	}

	switch (ACTION) {
		case ACTION_SET.GET_MOCKTEST_DATA:
			result = await getMockData();
			break;
		case ACTION_SET.OPEN_ALL_JIGOU_QUESLIST:
			result = await openAllQlist()
			break;
		case ACTION_SET.CHECK_USER_ACTIVITY:
			result = await checkUserActivity()
			break
		case ACTION_SET.GET_BANNER:
			result = await getBanner()
			break;
		case ACTION_SET.GET_VIDEO:
			result = await getVideo()
			break;
		case ACTION_SET.GET_HOME:
			result = await getHome()
			break;
		case ACTION_SET.GET_ERROR_COUNT:
			result = await getErrorCount()
			break;
		default:
			break;
	}

	//返回数据给客户端
	return {
		code: 1,
		data: result,
		errMsg: ''
	};
};
